#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import urllib2
import urllib
import cookielib
import StringIO
import gzip
import time
import requests
from lxml import html


def gz_decode(data):
    compressedstream = StringIO.StringIO(data)
    gziper = gzip.GzipFile(fileobj=compressedstream)
    data = gziper.read()
    return data


login_url = r'http://login.jiayuan.com'
request_headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                   'Accept-Encoding':'gzip,deflate',
                   'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                   'Connection':'keep-alive',
                   'Host':'login.jiayuan.com',
                   'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
                   }
response = requests.get(login_url, headers=request_headers)

xpath = r'//*[@id="login"]/input[1]'
doc = html.document_fromstring(response.text)
doms = doc.xpath('//*[@id="login"]/input[1]')
print
print doms[0].value


passport_url = r'https://passport.jiayuan.com/dologin.php?pre_url=http://www.jiayuan.com/usercp'
def login():
    post_data = {'name':'baixuexue123@sina.com',
               'password': 'xuebailove321',
               '_s_x_id': doms[0].value,
               'm_p_l': '1',
               'ljg_login': '1',
               'position': '0',
               'channel': '0',
               'remem_pass': 'on',
               }
    post_data = urllib.urlencode(post_data)
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
               'Accept-Encoding':'gzip,deflate',
               'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
               'Connection':'keep-alive',
               'Cache-Control': 'no-cache',
               'Content-Type': 'application/x-www-form-urlencoded',
               'Referer':'http://login.jiayuan.com/',
               'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
               }
    req = urllib2.Request(passport_url, post_data, headers)
    time.sleep(5)
    response = opener.open(req)
    print response.geturl()
    print response.info().getheader('Set-Cookie')
    content = response.read()
    print gz_decode(content)

if __name__ == '__main__':
    login()
